<!-- 气温监测报警 -->
<!-- 初步完成 2024-10-8 -->
<template>
    <div class="container">
        <div style="display: flex; align-items: center; padding: 10px; color: #fff;">
            <span style="margin-right: 20px; font-weight: bold;">天气实况监测</span>
            <span style="margin-right: 20px;">|</span>
            <span style="display: flex; align-items: center;">
                <span>气温监测报警</span>
            </span>

        </div>
        <div class='title'>
            <span>{{ station_user }}自动气象站温度</span>
        </div>

        <div class="select">
            <span style="font-size: 16px;color: white;margin: 0 10px">从</span>
            <el-date-picker v-model="startTime" type="datetime" placeholder="选择日期时间" style="width:200px"
                value-format="yyyy-MM-dd HH:mm:ss" class="custom-select" size="small">
            </el-date-picker>
            <span style="font-size: 16px;color: white;margin: 0 10px">至</span>
            <el-date-picker v-model="endTime" type="datetime" placeholder="选择日期时间" style="width:200px"
                value-format="yyyy-MM-dd HH:mm:ss" class="custom-select" size="small">
            </el-date-picker>

            <span style="font-size: 16px;color: white;margin: 0 10px">显示温度>=
                <el-select v-model="showTemp" style="width:70px" class="custom-select" size="small">
                    <el-option v-for="item in showTempOptions" :key="item.value" :label="item.value"
                        :value="item.value">
                    </el-option>
                </el-select></span>
            <el-button style="background-color: #243665;color: white;font-weight: bold" size="small"
                @click="getTempData(time)">确定</el-button>
            <span style="font-size: 16px;color: white;margin: 0 10px">小于0度是否报警</span>
            <el-switch v-model="call" active-color="#008dd4" inactive-color="#dcdfe6">
            </el-switch>
            <!-- 语音报警 -->
            <audio src="@/assets/monitor/wd.mp3" id="mp3"></audio>

        </div>

        <div class="buttons">
            <el-button style="background-color: #243665;color: white;font-weight: bold" size="small"
                @click="getTempData('minute')">当前小时分钟温度</el-button>
            <el-button style="background-color: #243665;color: white;font-weight: bold" size="small"
                @click="getTempData('1h')">1小时</el-button>
            <el-button style="background-color: #243665;color: white;font-weight: bold" size="small"
                @click="getTempData('3h')">3小时</el-button>
            <el-button style="background-color: #243665;color: white;font-weight: bold" size="small"
                @click="getTempData('6h')">6小时</el-button>
            <el-button style="background-color: #243665;color: white;font-weight: bold" size="small"
                @click="getTempData('12h')">12小时</el-button>
            <el-button style="background-color: #243665;color: white;font-weight: bold" size="small"
                @click="getTempData('24h')">24小时</el-button>
            <!-- <el-button style="background-color: #243665;color: white;font-weight: bold" size="small">显示热力图</el-button>
            <el-button style="background-color: #243665;color: white;font-weight: bold" size="small">关闭热力图</el-button> -->

        </div>
        <div class="content">
            <div class="left">

                <!-- 站点总览 -->
                <div class="siteOverview">

                    <div class="title">
                        <span>站点总览</span>
                    </div>
                    <div class="content">

                        <el-table :data="tableData" ref="table" style="width: 100%" height="100%"
                            :header-cell-style="headerCellStyle" :cell-style="cellStyle" :row-style="rowStyle">

                            <el-table-column prop="county" label="县名" min-width="20%" align="center">
                            </el-table-column>
                            <!-- <el-table-column prop="wsName" label="站名" min-width="30%" align="center">
                                <template slot-scope="scope">
                                    <span style="cursor:pointer;color:#008ed0"
                                        @click="getHistoryData(scope.row)">{{ scope.row.wsName }}</span>
                                </template>

</el-table-column> -->
                            <el-table-column prop="wsName" label="站名" min-width="30%" align="center">

                            </el-table-column>
                            <el-table-column prop="temperature" label="平均温度" min-width="30%" align="center">
                            </el-table-column>
                            <el-table-column prop="detail" label="详情" min-width="20%" align="center">
                                <template slot-scope="scope">
                                    <span @click="goToDetail(scope.row)" style="cursor:pointer;color:#61afef">详情</span>
                                </template>

                            </el-table-column>

                        </el-table>
                    </div>

                </div>
                <!-- 站点统计 -->
                <div class="siteStatistics">

                    <div class="title">
                        <span>气温统计</span>
                    </div>
                    <div class="content">
                        <span>小于0度的站有{{ tempStatistics?.temp0 }}个</span>
                        <span>0-4.9度的站有{{ tempStatistics?.temp4_9 }}个</span>
                        <span>5-9.9度的站有{{ tempStatistics?.temp9_9 }}个</span>
                        <span style="color:#24acf2">10-19.9度的站有{{ tempStatistics?.temp19_9 }}个</span>
                        <span style="color:#db7079">大于20度的站有{{ tempStatistics?.temp20 }}个</span>
                        <span>最高温度点:{{
                            `${stationData[0]?.county}${stationData[0]?.wsName}${stationData[0]?.temperature}度`
                        }}</span>
                        <span>次高温度点:{{
                            `${stationData[1]?.county}${stationData[1]?.wsName}${stationData[1]?.temperature}度`
                        }}</span>
                    </div>

                </div>
            </div>
            <!-- 地图 -->
            <div class="map">
                <div id="map" ref="map">

                </div>
            </div>
            <div class="right">
                <!-- 历史气温 -->
                <div class="historicalRainfall">

                    <div class="title">
                        <span>历史气温</span>
                    </div>
                    <div class="name">
                        <span>{{ selectedHistoryStation }}</span>
                    </div>
                    <div class="content">

                        <el-table :data="historyTableData" ref="table" style="width: 100%" height="100%"
                            :header-cell-style="headerCellStyle" :cell-style="cellStyle" :row-style="rowStyle">
                            <el-table-column prop="tt" label="时间" min-width="50%" align="center">
                            </el-table-column>
                            <el-table-column prop="bc" label="温度" min-width="25%" align="center">
                            </el-table-column>
                            <el-table-column prop="bcmx" label="最高" min-width="25%" align="center">
                            </el-table-column>
                        </el-table>

                    </div>

                </div>

            </div>
        </div>

    </div>
</template>

<script>
import { reqTempStation, reqStationDetail } from '@/api/monitor/index.js'
import Cookies from 'js-cookie';
import axios from "axios";
import * as echarts from 'echarts';
import Charts from '@jiaminghi/charts'
// 雅安地图边界
import yaan from './yaan.json'




import "ol/ol.css";

import { fromLonLat, transformExtent } from "ol/proj";


import XYZ from 'ol/source/XYZ';
import TileLayer from "ol/layer/Tile";
import VectorLayer from "ol/layer/Vector";
import VectorSource from "ol/source/Vector";
import { Map, View, Feature } from "ol";
import { Style, Stroke, Fill, Text, Icon, Circle } from "ol/style";
import { Polygon, MultiPolygon, Point } from "ol/geom";
import { getTransform } from 'ol/proj';
import { defaults } from "ol/control";
import { Vector } from 'ol/source.js'
import OlGeomPoint from 'ol/geom/Point'
import OlStyleStyle from 'ol/style/Style'
import OlStyleIcon from 'ol/style/Icon'
import Vectors from 'ol/layer/Vector.js'
import Overlay from 'ol/Overlay.js'
import ImageLayer from 'ol/layer/Image';
import ImageStatic from 'ol/source/ImageStatic';
import Attribution from 'ol/control/Attribution';
import Projection from 'ol/proj/Projection'; // 导入 Projection 类  
// 处理时间格式
import moment from 'moment';
export default {
    data() {
        return {
            // 用户站点
            station_user: Cookies.get('station_user'),
            //开始时间
            startTime: moment(new Date(new Date().getTime() - (100 * 3600 * 24 * 1000))).format('YYYY-MM-DD HH:mm:ss'),
            // 结束时间
            endTime: moment(new Date()).format('YYYY-MM-DD HH:mm:ss'),

            //显示气温
            showTemp: -20,
            showTempOptions: [{ value: -20 }, { value: -10 }, { value: 0 }, { value: 25 }, { value: 30 },],
            // 是否报警
            call: true,
            // 显示气温的时间
            time: '',

            map: null,
            // 图层
            currentLayer: null,

            // 选中的站点
            select_station: null,
            // 站点id
            select_station_id: null,
            // 站点数据
            stationData: [],
            // 气温统计
            tempStatistics: null,

            // 站点总览表格数据
            tableData: [
                {
                    coordinates: [],
                    county: '',
                    rainFall: '',
                    wsName: ''
                }
            ],
            // 历史数据
            historyTableData: [],
            // 选择的历史数据站点
            selectedHistoryStation: '',
        }
    },
    mounted() {

        this.getTempData('minute')
        this.initMap()
        this.addArea(yaan)
        this.addHighSpeed()
        this.stationClick()
    },
    methods: {
        // 获取所有站点数据
        async getTempData(time = this.time) {
            this.time = time
            let body = {
                begin: this.startTime,
                end: this.endTime,
                user: this.station_user,
                time
            }
            let res = await reqTempStation(body)

            if (res.data.code === 500) {
                this.$message.error(res.data.msg)
            }
            else {
                this.tableData = res.data.data
                this.stationData = res.data.data
                this.tempStatistics = res.data.fractionalTemperatureData

                this.stationData.sort(function (a, b) {
                    return b.temperature - a.temperature
                })


                this.markStations(this.stationData)
                this.getHistoryData(this.stationData[0])

                // 语音报警
                this.stationData.some((item) => {
                    if (item.temperature < 0 && this.call) {
                        let audio = document.getElementById("mp3");
                        audio.play();
                        return
                    }
                })
            }
        },

        // 获取某个站点历史数据
        async getHistoryData(station) {
            this.selectedHistoryStation = station.wsName
            let res = await reqStationDetail(station.wsId)
            this.historyTableData = res.data.details
        },
        // 初始化地图
        initMap() {

            this.map = new Map({
                target: "map",
                controls: defaults({
                    zoom: true
                }).extend([]),
                layers: [
                    new TileLayer(
                        {
                            source: new XYZ({
                                className: 'blueLayer',
                                url:
                                    // 高德
                                    'https://webrd04.is.autonavi.com/appmaptile?lang=zh_cn&size=1&scale=1&style=8&x={x}&y={y}&z={z}',
                                tileLoadFunction: function (imageTile, src) {
                                    // 使用滤镜 将白色修改为深色
                                    let img = new Image()
                                    // img.crossOrigin = ''
                                    // 设置图片不从缓存取，从缓存取可能会出现跨域，导致加载失败
                                    img.setAttribute('crossOrigin', 'anonymous')
                                    img.onload = function () {
                                        let canvas = document.createElement('canvas')
                                        let w = img.width
                                        let h = img.height
                                        canvas.width = w
                                        canvas.height = h
                                        let context = canvas.getContext('2d')
                                        context.filter = 'grayscale(100%) invert(100%) sepia(10%) hue-rotate(180deg) saturate(2000%) brightness(120%) contrast(100%)'
                                        context.drawImage(img, 0, 0, w, h, 0, 0, w, h)
                                        imageTile.getImage().src = canvas.toDataURL('image/png')
                                    }
                                    img.src = src
                                },


                            }),

                        },
                        { zoomOffset: 1 }
                    )
                ],
                view: new View({
                    center: fromLonLat([102.6879955, 30.021841]),
                    zoom: 10.5,

                    minZoom: 9,

                }),


            });

            //离线


        },
        // 描边雅安市
        addArea(geo = []) {
            console.log(geo)
            if (geo.length == 0) return false;
            let areaFeature = null;
            // 设置图层
            this.areaLayer = new VectorLayer({
                source: new VectorSource({
                    features: []
                })
            });
            // 添加图层
            this.map.addLayer(this.areaLayer);
            geo[0].features.forEach(g => {

                let lineData = g
                if (lineData.geometry.type == "MultiPolygon") {
                    areaFeature = new Feature({
                        geometry: new MultiPolygon(
                            lineData.geometry.coordinates
                        ).transform("EPSG:4326", "EPSG:3857")
                    });
                } else if (lineData.geometry.type == "Polygon") {
                    areaFeature = new Feature({
                        geometry: new Polygon(
                            lineData.geometry.coordinates
                        ).transform("EPSG:4326", "EPSG:3857")
                    });
                }
                areaFeature.setStyle(
                    new Style({
                        // fill: new Fill({ color: "#00b07c30" }),
                        stroke: new Stroke({
                            width: 3,
                            color: 'gray'
                        })
                    })
                );
                this.areaLayer.getSource().addFeatures([areaFeature]);
            });


        },
        // 叠加高速
        addHighSpeed() {

            // 定义高速路叠加图层的范围（西南角和东北角）  
            let sw = fromLonLat([102.011052, 29.941536]); // 西南角  
            let ne = fromLonLat([103.1212939, 30.084146]); // 东北角  
            const extent = [
                sw[0], // minX  
                sw[1], // minY  
                ne[0], // maxX  
                ne[1]  // maxY  
            ];
            // 创建图片叠加图层  
            let imageLayer = new ImageLayer({
                source: new ImageStatic({
                    url: require('@/assets/monitor/yakang.png'), // 图片地址  
                    imageExtent: extent
                }),
                opacity: 0.6 // 设置透明度  
            });

            // 添加图片叠加图层到地图  
            this.map.addLayer(imageLayer);

        },
        headerCellStyle() {
            return {
                background: "#000612",
                color: "#fff",
                // opacity: 0.8,
                fontSize: '12px'

            };
        },
        cellStyle() {
            return {
                fontSize: '12px',
                color: "#fff",
                // opacity: 0.8,
                background: "#000000",

            };
        },
        rowStyle() {
            return {
                height: "30px",
                color: "#000",
            };
        },

        // 标注样式
        createLabelStyle(feature, color) {
            //返回一个样式
            return new OlStyleStyle({
                //图标样式
                image: new OlStyleIcon({
                    anchor: [10, 18],      //设置图标偏移
                    scale: 0.6,      // 图标缩小显示
                    anchorOrigin: 'top-right',     //标注样式的起点位置
                    anchorXUnits: 'pixels',    //X方向单位：分数
                    anchorYUnits: 'pixels',     //Y方向单位：像素
                    offsetOrigin: 'bottom-left',   //偏移起点位置的方向
                    opacity: 0.9,    //透明度
                    src: feature.get('img')     //图片路径
                }),
                //文本样式
                text: new Text({
                    textAlign: 'center',     //对齐方式
                    textBaseline: 'middle',    //文本基线
                    font: 'bold 12px 微软雅黑',     //字体样式
                    text: feature.get('name'),    //文本内容
                    offsetY: -25,    // Y轴偏置
                    fill: new Fill({        //填充样式
                        color,

                    }),

                    backgroundFill: new Fill({      // 填充背景
                        color: '#fff',

                    }),

                    padding: [3, 3, 3, 3],
                }),
                // 设置层级
                zIndex: 199
            });
        },
        // 地图上标注站点
        markStations(data) {
            // 删除覆盖物
            this.map.removeLayer(this.currentLayer);

            const source = new Vector(); // 初始化矢量数据源


            data = data.filter((item) => {
                return item.temperature >= this.showTemp
            })

            console.log('data', data)

            // 根据预警信号显示不同图标
            data.forEach((item) => {
                const feature = new Feature({
                    geometry: new OlGeomPoint(fromLonLat([item.coordinates[0], item.coordinates[1]])),
                    name: item.county + item.wsName + ' : ' + item.temperature + ' ℃',
                    img: require(`@/assets/travel/站点.svg`),
                    type: 'station',
                    wsId: item.wsId
                });

                feature.setId(item.wsId);
                feature.setStyle(this.createLabelStyle(feature, '#000'));
                source.addFeature(feature); // 将标签要素添加至矢量数据源
            })

            this.currentLayer = new Vectors({               // 创建矢量图层
                source: source,
                zIndex: 999
            })

            this.map.addLayer(this.currentLayer)              // 将矢量图层添加至地图
        },


        // 点击站点
        stationClick() {
            this.map.on('click', (evt) => {
                var pixel = this.map.getEventPixel(evt.originalEvent);
                var feature = this.map.forEachFeatureAtPixel(pixel, (feature, layer) => {
                    return feature;
                });

                if (feature) {

                    if (feature.get('type') && feature.get('type') === 'station') { // 更改为你自己生成的marker类型
                        // 改变选中的站点
                        this.select_station_id = feature.get('wsId')

                        this.select_station = this.stationData.filter((item) => {
                            return item.wsId === this.select_station_id
                        })[0]
                        this.getHistoryData(this.select_station)
                        // 1. 聚焦到某经纬度
                        this.map.getView().animate({
                            zoom: 13, // 地图层级
                            center: fromLonLat([this.select_station.coordinates[0], this.select_station.coordinates[1]]), // 聚焦位置
                            duration: 1000, // 过渡时间

                        })
                    }


                }

            });


            // 鼠标移上地图变手
            this.map.on('pointermove', e => {
                this.map.getTargetElement().style.cursor = 'pointer'
            });


        },

        // 跳转单站查询
        goToDetail(item) {

            this.$router.push(
                {
                    path: 'monitoring_alarm_detail',
                    query: {
                        title: '气温监测预警',
                        wsId: item.wsId

                    }
                })

        }


    },
}
</script>

<style scoped lang="scss">
.el-table {
    width: 100%;


    .el-table__header-wrapper table,
    .el-table__body-wrapper table {
        width: 100% !important;

    }

    .el-table__body,
    .el-table__footer,
    .el-table__header {
        table-layout: auto;
    }
}

::v-deep.el-table__body-wrapper::-webkit-scrollbar {
    width: 0;
    border: none;
}

::v-deep .el-table__body-wrapper {

    // 整个滚动条
    &::-webkit-scrollbar {
        width: 0px; // 纵向滚动条的宽度
        background: rgba(213, 215, 220, 0.3);
        border: none;
    }

    // 滚动条轨道
    &::-webkit-scrollbar-track {
        border: none;
    }
}

// --------------------隐藏table gutter列和内容区右侧的空白 start
::v-deep .el-table th.gutter {
    display: none;
    width: 0
}

::v-deep .el-table colgroup col[name='gutter'] {
    display: none;
    width: 0;
}

// 这个样式不加的话内容哪里会缺一点，估计是因为滚动条哪里缺的没有补上
::v-deep .el-table__body {
    width: 100% !important;
}

// --------------------隐藏table gutter列和内容区右侧的空白 end


.container {
    width: 100%;
    height: 100%;
    box-sizing: border-box;


    .title {
        width: 100%;
        height: 35px;
        display: grid;
        place-items: center;

        span {
            color: white;
            font-size: 22px;
            font-weight: bold
        }
    }

    .select {
        display: flex;
        justify-content: center;
        align-items: center;
        width: 100%;
        height: 35px;

    }

    .buttons {
        display: flex;
        justify-content: center;
        align-items: center;
        width: 100%;
        height: 35px;
    }

    .content {
        width: 100%;
        height: 760px;
        display: flex;
        flex-wrap: nowrap;
        margin: 0 auto;

        .left {
            width: 20%;
            height: 100%;
            display: flex;
            flex-wrap: wrap;
            flex-direction: column;
            align-items: center;
            justify-content: space-between;


            .siteOverview {
                width: 90%;
                height: 45%;
                border: 10px solid transparent;
                border-image: url('@/assets/border.png') 20 round;

                .title {
                    width: 100%;
                    height: 8%;
                    display: flex;
                    justify-content: space-between;
                    align-items: center;
                    background: url('@/assets/input.png');
                    background-size: contain;
                    background-repeat: no-repeat;

                    span {
                        font-size: 17px;
                        color: white;
                        letter-spacing: 2px;
                        color: white;
                        font-weight: bold;
                        margin: 0 10px;
                        display: flex;
                        justify-content: center;
                        align-items: center;

                    }
                }

                .content {
                    width: 100%;
                    height: 85%;
                }
            }

            .siteStatistics {

                width: 90%;
                height: 45%;
                border: 10px solid transparent;
                border-image: url('@/assets/border.png') 20 round;

                .title {
                    width: 100%;
                    height: 8%;
                    display: flex;
                    justify-content: space-between;
                    align-items: center;
                    background: url('@/assets/input.png');
                    background-size: contain;
                    background-repeat: no-repeat;

                    span {
                        font-size: 17px;
                        color: white;
                        letter-spacing: 2px;
                        color: white;
                        font-weight: bold;
                        margin: 0 10px;
                        display: flex;
                        justify-content: center;
                        align-items: center;

                    }
                }

                .content {
                    width: 100%;
                    height: 85%;
                    display: flex;
                    flex-wrap: wrap;

                    justify-content: center;
                    align-items: center;
                    padding: 20px;


                    span {
                        width: 100%;
                        height: 14%;
                        color: white;
                    }
                }
            }
        }

        .map {
            width: 60%;
            height: 100%;

            #map {
                width: 100%;
                height: 100%;
            }
        }

        .right {
            width: 20%;
            height: 100%;
            display: flex;
            flex-wrap: wrap;
            flex-direction: column;
            align-items: center;
            justify-content: space-between;

            .historicalRainfall {
                width: 90%;
                height: 100%;
                border: 10px solid transparent;
                border-image: url('@/assets/border.png') 20 round;

                .title {
                    width: 100%;
                    height: 3%;
                    display: flex;
                    justify-content: space-between;
                    align-items: center;
                    background: url('@/assets/input.png');
                    background-size: contain;
                    background-repeat: no-repeat;

                    span {
                        font-size: 17px;
                        color: white;
                        letter-spacing: 2px;
                        color: white;
                        font-weight: bold;
                        margin: 0 10px;
                        display: flex;
                        justify-content: center;
                        align-items: center;

                    }
                }

                .name {
                    width: 100%;
                    height: 5%;
                    display: grid;
                    place-items: center;

                    span {
                        font-size: 16px;
                        color: white;
                        font-weight: bold;

                    }
                }

                .content {
                    width: 100%;
                    height: 90%;
                    display: flex;
                    flex-wrap: wrap;
                    justify-content: center;
                    align-items: center;
                }
            }


        }
    }
}
</style>